<?php
/**
 * @name 销售单Service
 * @Author : yu
 * @Created : 2016-11-1
 * @Copyright : MPE.Fiidee.Monda.Cn
 */
namespace trading\service;

use herosphp\core\Loader;
use herosphp\utils\Page;
use models\TradingOrderModel;
use utils\x1\MyFunction;
use utils\x1\MyNumber;

Loader::import('models.TradingOrderModel');

Loader::import('utils.x1.MyFunction');


class SaleService extends CommonService
{
    private $thisModel = null;

    public function __construct()
    {
        $this->thisModel = Loader::model('tradingSale');

        Loader::model('tradingOrder');//引入TradingOrderModel类
    }

    //销售单搜索
    public function search($pagesize, $page, $search_arr)
    {

        $offset = $pagesize * ($page - 1); //计算记录偏移量

        $whereSql = "And sale.app_id='" . appId() . "'";

        //单选导出 add by Laoliu
        if ($search_arr['id']) {
            $whereSql .= " AND sale.id in {$search_arr['id']}";
        }
        if ($search_arr['start_time'] != '' || $search_arr['end_time'] != '') {

            $whereSql .= " And " . MyFunction::betweenSqlByTime('unix_timestamp(contract.signed_time)', strtotime($search_arr['start_time']), strtotime($search_arr['end_time']));

        }

        if (in_array($search_arr['select_mix_option1'], array('contract_no', 'order_no', 'sale_no', 'invoice_no'))) {
            switch ($search_arr['select_mix_option1']) {
                case 'contract_no':
                    $whereSql .= " And contract.{$search_arr['select_mix_option1']} Like '%{$search_arr['select_mix_option_value1']}%'";
                    break;

                case 'order_no':
                    $whereSql .= " And o.{$search_arr['select_mix_option1']} Like '%{$search_arr['select_mix_option_value1']}%'";
                    break;

                case 'sale_no':
                    $whereSql .= " And sale.{$search_arr['select_mix_option1']} Like '%{$search_arr['select_mix_option_value1']}%'";
                    break;

                case 'invoice_no':
                    $whereSql .= " And invoice.{$search_arr['select_mix_option1']} Like '%{$search_arr['select_mix_option_value1']}%'";
                    break;
            }
        }

        if (($search_arr['start_time'] != '' || $search_arr['end_time'] != '') && in_array($search_arr['select_mix_option2'], array('order_time', 'pay_time', 'delivery_time'))) {
            switch ($search_arr['select_mix_option2']) {
                case 'order_time':
                    $whereSql .= " And " . MyFunction::betweenSqlByTime('unix_timestamp(o.order_time)', strtotime($search_arr['start_time']), strtotime($search_arr['end_time']));
                    break;

                case 'pay_time':
                    $whereSql .= " And " . MyFunction::betweenSqlByTime('unix_timestamp(o.pay_time)', strtotime($search_arr['start_time']), strtotime($search_arr['end_time']));
                    break;

                case 'delivery_time':
                    $whereSql .= " And " . MyFunction::betweenSqlByTime('unix_timestamp(invoice.delivery_time)', strtotime($search_arr['start_time']), strtotime($search_arr['end_time']));
                    break;

            }
        }

        $count_sql = "Select  count(*)
                From trading_sale  As sale
                Left Join trading_contract as contract On contract.order_id=sale.order_id
                Left Join trading_order As o On sale.order_id=o.id
                Left Join trading_invoice As invoice On invoice.order_id=o.id
                Left Join member As m On m.id=o.member_id
                Where 1 $whereSql";

        $total = $this->thisModel->getDB()->excute($count_sql)->fetchColumn();


        //分页查询
        $pageinationSql = isset ($offset) ? " Limit $offset,$pagesize" : " Limit 0,$pagesize";

        $sql = "Select contract.*,sale.*,sale.id as sale_id,o.*,m.username,invoice.invoice_no,invoice.delivery_time
                 From trading_sale  As sale
                Left Join trading_contract as contract On contract.order_id=sale.order_id
                Left Join trading_order As o On sale.order_id=o.id
                Left Join trading_invoice As invoice On invoice.order_id=o.id
                Left Join member As m On m.id=o.member_id
                Where 1 $whereSql
                Order By contract.signed_time Desc $pageinationSql";

        $items = $this->thisModel->getDB()->excute($sql)->fetchAll($fetch_style = 2);


        return array("items" => $items, "total" => $total);
    }

    //销售排行列表
    public function searchByRanking($pagesize, $page, $search_arr)
    {
        $offset = $pagesize * ($page - 1); //计算记录偏移量

        $status = TradingOrderModel::ORDER_STATUS_COMPLETED;

        $whereSql = " And p.app_id='" . appId() . "' And o.order_status='" . $status . "'";

        //单选导出 add by Laoliu
        if ($search_arr['ids']) {
            $whereSql .= " AND p.id in {$search_arr['ids']}";
        }

        if ($search_arr['start_time'] != '' || $search_arr['end_time'] != '') {

            $whereSql .= " And " . MyFunction::betweenSqlByTime('unix_timestamp(o.order_time)', strtotime($search_arr['start_time']), strtotime($search_arr['end_time']));
        }

        if (in_array($search_arr['select_mix_option1'], array('product_no'))) {
            switch ($search_arr['select_mix_option1']) {
                case 'product_no':
                    $whereSql .= " And p.{$search_arr['select_mix_option1']} Like '%{$search_arr['select_mix_option_value1']}%'";
                    break;
            }
        }

        $count_sql = "Select  p.id
                From product As p
                Left Join trading_order_product As o_p On o_p.product_id=p.id
                Left Join trading_order As o On o.id=o_p.order_id
                Where 1 $whereSql GROUP By p.product_no";
        $total_items = $this->thisModel->getDB()->excute($count_sql)->fetchAll($fetch_style = 2);
        $total = count($total_items);
        // $total = $this->thisModel->getDB()->excute($count_sql)->fetchColumn();

        //分页查询
        $pageinationSql = isset ($offset) ? " Limit $offset,$pagesize" : " Limit 0,$pagesize";

        $sql = "Select sum(o_p.product_actual_price) As total_sale_amount,sum(p.cost_price*o_p.product_quantity) As total_cost_price,sum(o_p.product_quantity) As total_sale_quantity,p.*
                From product As p
                Left Join trading_order_product As o_p On o_p.product_id=p.id
                Left Join trading_order As o On o.id=o_p.order_id
                Where 1 $whereSql
                GROUP By p.product_no Order By total_sale_quantity DESC $pageinationSql";


        $items = $this->thisModel->getDB()->excute($sql)->fetchAll($fetch_style = 2);


        return array("items" => $items, "total" => $total);
    }

    //销售明细
    public function searchByDetails($pagesize, $page, $search_arr)
    {

        $offset = $pagesize * ($page - 1); //计算记录偏移量

        $whereSql = "And o.app_id='" . appId() . "' And o.order_status='7'";

        if ($search_arr['start_time'] != '' || $search_arr['end_time'] != '') {

            $whereSql .= " And " . MyFunction::betweenSqlByTime('unix_timestamp(o.order_time)', strtotime($search_arr['start_time']), strtotime($search_arr['end_time']));

        }

        //单选导出 add by Laoliu
        if ($search_arr['ids']) {
            $whereSql .= " AND o.id in {$search_arr['ids']}";
        }

        if (in_array($search_arr['select_mix_option1'], array('order_no', 'product_no'))) {
            switch ($search_arr['select_mix_option1']) {
                case 'order_no':

                    $whereSql .= " And o.{$search_arr['select_mix_option1']} Like '%{$search_arr['select_mix_option_value1']}%'";
                    break;
                case 'product_no':

                    $whereSql .= " And p.{$search_arr['select_mix_option1']} Like '%{$search_arr['select_mix_option_value1']}%'";
                    break;
            }
        }

        $count_sql = "Select  count(*)
                From trading_order_product As o_p
                Left Join trading_order as o On o_p.order_id=o.id
                Left Join product As p On o_p.product_id=p.id
                Where 1 $whereSql";
        $total = $this->thisModel->getDB()->excute($count_sql)->fetchColumn();

        //分页查询
        $pageinationSql = isset ($offset) ? " Limit $offset,$pagesize" : " Limit 0,$pagesize";

        $sql = "Select o_p.product_actual_price As sale_amount,o_p.cost_price,o_p.product_quantity As sale_quantity,o.id as order_id,
                o.order_no,o.pay_way,o.order_time,p.product_name,p.brand_name,p.factory_name,p.type_name,p.product_no,p.pkg_size
                From trading_order_product As o_p
                Left Join trading_order as o On o_p.order_id=o.id
                Left Join product As p On o_p.product_id=p.id
                Where 1 $whereSql ORDER BY order_time DESC
                $pageinationSql";

        $items = $this->thisModel->getDB()->excute($sql)->fetchAll($fetch_style = 2);
        foreach ($items as $k => $item) {

            //$items[$k]['sale_profit']=$items[$k]['sale_profit']-$items[$k]['cost_price']*$items[$k]['sale_quantity'];

        }
        return array("items" => $items, "total" => $total);
    }

    /**
     * 订单生成销售单
     * @param $member_id 订单用户id
     * @param $order_id 订单id
     * @return int
     */
    public function addSale($order_id)
    {

        if ($this->thisModel->getItem(array('order_id' => $order_id))) {

            return false;

        } else {

            $myNumber = new MyNumber(appId());
            $sale_no = $myNumber->build_no('xs');//生成销售单号

            $addData = array(
                "sale_no" => $sale_no,
                "order_id" => $order_id,
            );
            return $this->thisModel->add($addData);
        }

    }

    /**
     * 获取指定时间段里的销售利润数据
     * @param $start_time
     * @param $end_time
     * @param $app_id
     * @return mixed
     */
    public function getTradingSaleProfitByDate($start_time, $end_time, $app_id)
    {

        $orderModel = Loader::model('tradingOrder');
        $order_status = TradingOrderModel::ORDER_STATUS_COMPLETED;
        $sql = "Select
sum(o.actual_amount) As total_sale_amount,
sum(p.cost_price*o_p.product_quantity) As total_cost_price
From trading_order As o
Left Join trading_order_product As o_p On o_p.order_id=o.id
Left Join product As p On p.id=o_p.product_id
Where o.app_id='$app_id' And o.order_status='$order_status' And '$start_time'<o.pay_time And o.pay_time<'$end_time'";
        //echo $sql;
        $items = $orderModel->query($sql);
        //计算总利润
        $items[0]['total_sale_profit'] = $items[0]['total_sale_amount'] - $items[0]['total_cost_price'];

        return $items[0];
    }

    //更新当天运营商的销售利润数据信息
    public function task_create_trading_sale_profit()
    {

        $app_ids = $this->getAllAppIdFromOrder();

        foreach ($app_ids as $app_id) {
            $that_day = date('Y-m-d');//当天时间
            $that_day_sta = date("Y-m-d 00:00:00", strtotime("$that_day -2 day"));
            $that_day_end = date("Y-m-d 23:59:59", strtotime($that_day));

            $saleProfitModel = Loader::model('tradingSaleProfit');

            $item = $this->getTradingSaleProfitByDate($that_day_sta, $that_day_end, $app_id);
            $data = array(
                'that_day' => $that_day,
                'cost_price' => setFloat($item['total_cost_price'], 2),
                'sales_price' => setFloat($item['total_sale_amount'], 2),
                'profit' => setFloat($item['total_sale_profit'], 2),
            );

            if ($saleProfitModel->getItem(array('app_id' => $app_id, 'that_day' => $that_day))) {

                //更新利润销售数据
                $saleProfitModel->updates($data, array('app_id' => $app_id, 'that_day' => $that_day));

            } else {
                $data['app_id']=$app_id;
                //插入利润销售数据
                $saleProfitModel->add($data);
            }
        }
        echo '执行成功--' . myNow();

    }

    /**
     * 获取所有appid
     * @return array
     */
    public function getAllAppIdFromOrder()
    {

        $app_ids = array();

        $orderModel = Loader::model('tradingOrder');

        $sql = "Select app_id From trading_order GROUP By app_id";

        $items = $orderModel->query($sql);

        foreach ($items as $k => $item) {

            $app_ids[] = $item['app_id'];
        }

        return $app_ids;

    }
}

